//
//  MyComplainController.m
//  PropertyMananger
//
//  Created by bh on 17/1/20.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "MyComplainController.h"
#import "MyComplainCell.h"
#import "MyComplainDetailController.h"
#import "MyComplainListModel.h"
#import "RightItemView.h"

@interface MyComplainController ()<RefreshStatusDelegate>
@property (nonatomic,strong) NSMutableArray * complainArray;//投诉数据数据源
@property (nonatomic,copy) NSString * selectedTime;//选择的的时间
@end

@implementation MyComplainController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self initTableViewWithView:self.view frame:CGRectMake(0, 44, BHscreenW, BHscreenH-64 - 44) isGroup:NO];
    self.tableView.backgroundColor = BHColor(238, 238, 238);
    self.tableView.showsVerticalScrollIndicator = NO;
    
    //暂无数据暂位图
    if (self.complainArray.count == 0) {
        
        UIView * lineView = [[UIView alloc]init];
        [self.tableView addSubview:lineView];
        lineView.backgroundColor = [BHColor(153, 153, 153)colorWithAlphaComponent:0.2];
        
        self.tableView.backgroundColor = [UIColor whiteColor];
        
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.view).with.offset(0);
            make.top.equalTo(self.view).with.offset(44);
            make.size.mas_equalTo(CGSizeMake(BHscreenW, 15));
        }];
        
    }

    [self getTime];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(timeClick:) name:timeNoticeCenter object:nil];
    
    self.complainArray = [[NSMutableArray alloc]init];
    
    [self createRefresh];
    
    [self postMyComplainData];

     [self createPlaceHolder];
    
}
#pragma mark - 接收通知传来的值
- (void)timeClick:(NSNotification *)noti{
    
    DLog(@" === %@",noti.userInfo[@"key"]);
    self.selectedTime = noti.userInfo[@"key"];
    self.isDown = YES;
    [self postMyComplainData];
    
}
- (void)dealloc
{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - 创建刷新UI
- (void)createRefresh{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.nextPage = 1;
        
        self.isDown = YES;
        //获取数据
         [self postMyComplainData];
        
    }];
    
    //上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.nextPage += 1;
        
        self.isDown = NO;
        //获取数据
        [self postMyComplainData];
        
        //    [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.complainArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    MyComplainCell * cell = [MyComplainCell cellWithTableView:tableView];
    MyComplainListModel * model = self.complainArray[indexPath.section];
    
    cell.complainCodeLabel.text = [NSString stringWithFormat:@"投诉编号: %@",model.ComplaintCode];
    cell.complianManLabel.text = model.ComplaintMan;
    cell.timeLabel.text = model.ComplaintTime;
    
    self.titleStr = @"投诉内容:";
    self.pingjieStr = [NSString stringWithFormat:@"%@ %@",self.titleStr,model.Contents];
    
    self.stra = [[NSMutableAttributedString alloc]initWithString:self.pingjieStr];//可随意拼接字符串
    [self.stra addAttributes:@{NSFontAttributeName:BHFont(15),NSForegroundColorAttributeName:BHColor(102, 102, 102)} range:NSMakeRange(0, self.titleStr.length)];
    cell.contentLabel.attributedText = self.stra;
    
    if ([model.ComplaintsProcessState isEqualToString:@"10"]) {
        
        cell.orderProgressLable.text = @"待处理";
        cell.orderProgressLable.textColor = [UIColor redColor];
        cell.orderProgressLable.layer.borderColor = [UIColor redColor].CGColor;
        
    }else if ([model.ComplaintsProcessState isEqualToString:@"20"]){
        
        cell.orderProgressLable.text = @"处理中";
        cell.orderProgressLable.textColor = BHColor(215, 152, 2);
        cell.orderProgressLable.layer.borderColor = BHColor(215, 152, 2).CGColor;
        
    }else if ([model.ComplaintsProcessState isEqualToString:@"30"]){
        cell.orderProgressLable.text = @"已处理";
        cell.orderProgressLable.textColor = BHColor(17, 177, 31);
        cell.orderProgressLable.layer.borderColor = BHColor(17, 177, 31).CGColor;
    }else if ([model.ComplaintsProcessState isEqualToString:@"40"]){
        cell.orderProgressLable.text = @"已回访";
        cell.orderProgressLable.textColor = BHColor(1, 181, 151);
        cell.orderProgressLable.layer.borderColor = BHColor(1, 181, 151).CGColor;
    }else if ([model.ComplaintsProcessState isEqualToString:@"50"]){
        cell.orderProgressLable.text = @"完成";
        cell.orderProgressLable.textColor = [UIColor redColor];
        cell.orderProgressLable.layer.borderColor =[UIColor redColor].CGColor;
    }

    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 210;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UITableViewHeaderFooterView * headerView = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"header"];
    
    return headerView;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyComplainDetailController * complainDetailVC = [[MyComplainDetailController alloc]init];
    complainDetailVC.model = self.complainArray[indexPath.section];
    complainDetailVC.delegate = self;
    [self.navigationController pushViewController:complainDetailVC animated:YES];
}
- (void)didRefreshDataToRepair{
    
    self.isDown = YES;
    [self postMyComplainData];
    DLog(@"重新请求数据");
}
#pragma mark - 数据请求
- (void)postMyComplainData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"努力加载数据中...";
    // 隐藏时从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.userInteractionEnabled = YES;
    NSDictionary * parms =  @{
                              @"CommunityID":userModel.CommunityID,
                              @"WorkerId":userModel.WorkerID,
                              @"QueryType":@"0",
                              @"Time":self.selectedTime,
                              @"Page":[NSString stringWithFormat:@"%ld",self.nextPage],
                              @"json":@"\{\"jsonEntity\":\{},\"action\":\"complaintlist\",\"version\":\"V1.0\"}"
                              };
    DLog(@"提交的参数 === %@",parms);
    
    [MineRequest postComplainListSuccess:^(id data) {
        [MBProgressHUD hideHUDForView:self.view];
        
        if (self.isDown == YES) {
            
            [self.complainArray removeAllObjects];
            self.isDown = NO;
        }
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"我的投诉单数据 == %@",array);
        for (NSDictionary * dict in array) {
            
            MyComplainListModel * model = [[MyComplainListModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [self.complainArray addObject:model];
        }

        if (self.complainArray.count != 0){
            
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;
            
        }else{
            
            self.placehoderImg.hidden = NO;
            self.titleLabel.hidden = NO;
        }
        if (self.complainArray.count <= 3) {
            
            self.tableView.mj_footer.hidden = YES;
        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        [self.tableView reloadData];
    } Fail:^(NSString *errorDes) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        [MBProgressHUD hideHUD];
        
    } param:parms ];
    
}
#pragma mark - 暂未图
- (void)createPlaceHolder
{
    self.placehoderImg = [[UIImageView alloc]init];
    [self.tableView addSubview:self.placehoderImg];
    self.placehoderImg.image = [UIImage imageNamed:@"ico_complaint_no"];
    
    [self.placehoderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.tableView.mas_bottom).with.offset(100);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    [self.tableView addSubview:self.titleLabel];
    self.titleLabel.text = @"暂无投诉单";
    
    self.titleLabel.textColor= BHColor(153, 153, 153);
    self.titleLabel.font = BHFont(15);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.placehoderImg.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(100, 25));
    }];
    
}
#pragma mark - 获取系统时间
- (void)getYearAndMonthData{
    
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSTimeInterval time = [zone secondsFromGMTForDate:date];
    NSDate *dateNow = [date dateByAddingTimeInterval:time];
    NSString * timeDataStr = [NSString stringWithFormat:@"%@",dateNow];
    DLog(@" === %@",dateNow);
    
    NSArray * arr = [timeDataStr componentsSeparatedByString:@"+"];
    DLog(@"日期格式化 == %@",arr[0]);
    
    NSArray * timeArr = [timeDataStr componentsSeparatedByString:@"-"];
    NSString * timeStr = [NSString stringWithFormat:@"%@-%@",timeArr[0],timeArr[1]];
    DLog(@"拼接好的时间===%@",timeStr);
    self.selectedTime = timeStr;
}
-(void)getTime{
    
    DLog(@"%@",self.parentViewController.navigationItem.rightBarButtonItem.customView);
    
    if(self.parentViewController.navigationItem.rightBarButtonItem.customView){
        RightItemView * rightView = self.parentViewController.navigationItem.rightBarButtonItem.customView;
        DLog(@"--------%@",rightView.timeLabel.text);
        
        self.selectedTime = rightView.timeLabel.text;
    }
    
}
@end
